package com.sinog.front.controller.biz;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sinog.core.model.JytjInfo;
import com.sinog.core.model.UserDTO;
import com.sinog.core.util.MapUtil;
import com.sinog.core.util.PageReturnUtil;
import com.sinog.core.utilbean.Constants;
import com.sinog.core.utilbean.Result;
import com.sinog.core.utilbean.ReturnCode;
import com.sinog.front.config.log.Log;
import com.sinog.front.controller.biz.common.CommonDownloadController;
import com.sinog.front.feign.biz.JytjService;
import com.sinog.front.service.user.UserFacade;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @desc 安帮工作资源管理 - 安帮资料信息管理 - 经验推介 - JytjController
 * @author zhangcb
 * @date -
 */
@Slf4j
@RestController
public class JytjController {

    @Autowired
    private UserFacade userFacade;
    @Resource
    private JytjService jytjService;
    @Resource
    private CommonDownloadController commonDownloadController;

    /**
     * 安帮工作资源管理 - 安帮资料信息管理 - 经验推介 - 获取首页经验推介列表
     * @return Map<String,Object>
     */
    @GetMapping("/basic/tzgg/getSyJytjList")
    public Map<String,Object> getSyJytjList() {
        UserDTO userDTO = userFacade.getAuthentication();
        List<HashMap<String,Object>> resultList = jytjService.getSyJytjList(userDTO.getAccount(),userDTO.getUsername(),userDTO.getLevel(),userDTO.getDepartid());
        //定义返回结果集合
        List<Map<String,Object>> returnList = new ArrayList<>(16);
        Map<String,Object> resmap = new HashMap<>(16);
        //循环经验推介列表
        for(HashMap<String,Object> stringObjectHashMap : resultList) {
            Map<String,Object> resultMap = new HashMap<>(16);
            //编号
            String id = stringObjectHashMap.get("id").toString();
            //todo 需要测试
            MapUtil.setValueMapToMap(stringObjectHashMap,resultMap,"id","title","fbdw","proid","adddate","enddate","type");
            //是否标红
            resultMap.put("titlecolor",Constants.NumberStr.NUM_STR_TWO);
            int count = Integer.parseInt(stringObjectHashMap.get("new").toString());
            if(Constants.Number.NUM_ZERO != count) {
                //是否被查看
                resultMap.put("new",Constants.NumberStr.NUM_STR_ONE);
            } else {
                //是否被查看
                resultMap.put("new",Constants.NumberStr.NUM_STR_TWO);
            }
            try {
                JytjInfo jytjInfo = jytjService.findJytjById(id);
                if(null == jytjInfo) {
                    resultMap.put("content","");
                } else {
                    resultMap.put("content",jytjInfo.getContent());
                }
                returnList.add(resultMap);
            } catch(RuntimeException e) {
                log.error("发生异常:{}",e.getMessage());
            }
        }
        resmap.put("error",Constants.Number.NUM_ZERO);
        resmap.put("data",returnList);
        resmap.put("msg","success");
        return resmap;
    }

    /**
     * 安帮工作资源管理 - 安帮资料信息管理 - 经验推介 - 列表
     * @param pageIndex pageIndex
     * @param pageSize pageSize
     * @param querykey querykey
     * @return String
     */
    @RequestMapping("/azbj/abzlxxgl/jytjInfoManage/list")
    public String getJytjInfoList(Integer pageIndex,Integer pageSize,
                                  @RequestParam(required = false, defaultValue = "-1") String querykey) {
        UserDTO authentication = userFacade.getAuthentication();
        Map<String,Object> mapkey = new HashMap<>(16);
        mapkey.put("account",authentication.getAccount());
        mapkey.put("level",authentication.getLevel().substring(1));
        mapkey.put("departId",authentication.getDepartid());
        mapkey.put("querykey",querykey);
        Page<Map<String,String>> page = jytjService.getJytjInfoList(pageIndex,pageSize,mapkey);
        for(int i = 0; i < page.getRecords().size(); i++) {
            Map resultMap = page.getRecords().get(i);
            String id = resultMap.get("id").toString();
            try {
                JytjInfo jytjInfo = jytjService.findJytjById(id);
                if(null == jytjInfo) {
                    resultMap.put("content","");
                } else {
                    resultMap.put("content",jytjInfo.getContent());
                }
                page.getRecords().set(i,resultMap);
            } catch(RuntimeException e) {
                log.error("发生异常:{}",e.getMessage());
            }
        }
        return PageReturnUtil.pageReturn(page);
    }

    /**
     * 安帮工作资源管理 - 安帮资料信息管理 - 经验推介 - 保存经验推介信息（修改/新增）
     * @param request request
     * @param data data
     * @return Result
     */
    @Log(type = "新增", value = "保存经验推介信息（修改/新增）")
    @PostMapping("/azbj/abzlxxgl/jytjInfoManage/save")
    public Result saveJytjInfo(HttpServletRequest request,
                               @RequestParam(required = false, defaultValue = "-1") String data) {
        boolean tag = jytjService.saveJytjInfo(data);
        if(tag) {
            return Result.success("保存成功");
        }
        return Result.failure(ReturnCode.SAVE_FAILED);
    }

    /**
     * 安帮工作资源管理 - 安帮资料信息管理 - 经验推介 - 删除
     * @param request request
     * @param id id
     * @param taskId taskId
     * @return Result
     */
    @Log(type = "删除", value = "删除经验推介信息")
    @DeleteMapping("/azbj/abzlxxgl/jytjInfoManage/delete")
    public Result deleteJytjInfo(HttpServletRequest request,String id,String taskId) {
        try {
            //删除经验推介表
            boolean deleteJytjInfo = jytjService.deleteJytjInfo(id);
            //删除附件信息
            Map<String,Object> map = new HashMap<>(2);
            map.put("id",id);
            map.put("taskId",taskId);
            boolean fjresult = commonDownloadController.deleteFjInfo(map);
            if(deleteJytjInfo && fjresult) {
                return Result.success("删除成功！");
            }
        } catch(RuntimeException e) {
            log.error("发生异常:{}",e.getMessage());
        }
        return Result.failure(ReturnCode.DELETE_FAILED);
    }

    /**
     * 安帮工作资源管理 - 安帮资料信息管理 - 经验推介 - 查询是否是自己发布的，编辑和删除只能操作自己发布的
     * @param id id
     * @return Result
     */
    @RequestMapping("/azbj/abzlxxgl/jytjInfoManage/checkIfOwnerPublish/{id}")
    public Result checkIfOwnerPublish(@PathVariable String id) {
        Map<String,Object> map = new HashMap<>(2);
        map.put("account",userFacade.getAuthentication().getAccount());
        map.put("id",id);
        int count = jytjService.checkIfOwnerPublish(map);
        if(Constants.Number.NUM_ZERO < count) {
            return Result.success();
        } else {
            return Result.failure(ReturnCode.FAILURE);
        }
    }

    /**
     * 安帮工作资源管理 - 安帮资料信息管理 - 经验推介 - 发布/取消发布
     * @param request request
     * @param id id
     * @param stateValue stateValue
     * @param account account
     * @return Result
     */
    @Log(type = "更新", value = "发布/取消发布-经验推介信息")
    @RequestMapping("/azbj/abzlxxgl/jytjInfoManage/setfabuState")
    public Result setfabuState(HttpServletRequest request,String id,String stateValue,String account) {
        String edituser = userFacade.getAuthentication().getAccount();
        if(account.equals(edituser)) {
            return jytjService.setfabuState(id,stateValue);
        }
        return Result.failure(ReturnCode.ZCWJ_NOT_CURRENT_USER);
    }
}